package com.zlsy.secondtime.threadcoreknowledge.threadobjectclasscommonmethods;


/**
 * @author zhouliang
 * @date 2020/5/17 17:18
 * <p>
 * 两个线程交替打印0~100的奇偶数，用wait和notify的方式
 */
public class WaitNotifyPrintOddEvenWait {

    private static int count;
    private static final Object LOCK = new Object();

    static class TurningRunner implements Runnable {

        @Override
        public void run() {
            //count =100的时候
            while (count <= 100) {
                //阻塞
                synchronized (LOCK) {
                    System.out.println(Thread.currentThread().getName() + "打印出:" + count);
                    count++;

                    //唤醒99，但是99还得不到执行
                    LOCK.notify();

                    //count = 101，于是跳过wait
                    if (count <= 100) {
                        try {
                            //释放 LOCK
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //虽然count = 101跳过了wait，但是此时线程正常执行完，会释放monitor，于是99wait会继续往下执行，然后也释放monitor，程序正常退出
                }
            }
        }
    }

    public static void main(String[] args) {
        TurningRunner r = new TurningRunner();
        Thread a = new Thread(r, "偶数");
        Thread b = new Thread(r, "奇数");
        a.start();
        b.start();
    }
}
